<?php

class ShippingtimeController extends Zend_Controller_Action
{

    public function init()
    {
        IndexController::initAdmin($this);
    }

    ////////////////////action function start//////////////////////////////
    public function indexAction()
    {
        
    }

    /**
     * list all rule
     */
    public function listruleAction()
    {
    	$data_type = $this->_getParam('data_type', 'rule_pending');
        $shippingTimeModel = new QShippingtime();
        $rules = $shippingTimeModel->getRules($data_type);

        // parse rule
        foreach ($rules as $key => &$rule)
        {
            // err
            $rule['err'] = 0;

            // condition
            $rule['conditions_parsed'] = $this->parseCondition($rule['conditions']);

            // action
            $rule['action_parsed'] = $this->parseAction($rule['action']);
        }
        //var_dump($rules);
        $this->view->rules = $rules;
        $this->view->data_type = $data_type;
    }

    /**
     * add a rule
     */
    public function createruleAction()
    {
        $shippingTimeModel = new QShippingtime();
        if ($this->_request->isPost())
        {
            $data = $_POST;

            // redirect to list rule if press cancel button
            if (isset($data['action']) && ($data['action'] == 'cancel'))
                $this->_redirect('shippingtime/listrule');

            // parse rule
            $rule = $this->parseRule($data);

            // insert
            $shippingTimeModel->insertRule($rule);

            //redirect
            if ($data['action'] == 'save_close')
                $this->_redirect('shippingtime/listrule');            
            elseif ($data['action'] == 'save')
            	$this->_redirect('shippingtime/createrule/order/null');
        }

        $this->view->maxId = $shippingTimeModel->getMaxIdRule() + 1;
        $this->view->maxOrder = isset($_GET['order']) ? $_GET['order'] : $shippingTimeModel->getMaxOrderRule() + 1;
    }

    /**
     * edit a rule
     */
    public function editruleAction()
    {
        $shippingTimeModel = new QShippingtime();
        if ($this->_request->isPost())
        {
            $data = $_POST;

            // redirect to list rule if press cancel button
            if (isset($data['action']) && ($data['action'] == 'cancel'))
                $this->_redirect('shippingtime/listrule');

            $rule = $this->parseRule($data);
            $rule_id = $data['rule_id'];

            // update rule
            $shippingTimeModel->updateRule($rule, $rule_id);

            // redirect
            if (isset($data['action']) && ($data['action'] == 'save_close'))
                $this->_redirect('shippingtime/listrule');
            else
                $this->_redirect("shippingtime/editrule/rule_id/" . $rule_id);
        }

        // get rule info
        $rule_id = $this->_getParam('rule_id');
        $rule_clone = $this->_getParam('rule_clone', 0);
        if ($rule_id == null)
        {
            $this->view->error = "rule id not found";
        } else
        {
            $rule_data = $shippingTimeModel->getRules('rule_pending', array('id' => $rule_id));
            $rule = $rule_data[0];
            
            if($rule_clone != 0){
                $new_rule = $rule;
                $new_rule['id'] = null;
                $new_rule['order'] = $rule['order'] + 1;
				$shippingTimeModel->insertRule($new_rule);
                $new_rule['id'] = $shippingTimeModel->getLastInsertId('rule', 'id');
                $rule = $new_rule;
            }

            // parse conditions
            $conditions_parsed = json_decode($rule['conditions'], true);
            if ($conditions_parsed != null)
            {
                foreach ($conditions_parsed as &$condition)
                {
                    $numberParam = $this->getOperatorNumberParam($condition['operator']);
                    if ($numberParam == 1)
                        $condition['params'] = $condition['params'][0];
                    else
                    {
                        $condition['params'] = implode(',', $condition['params']);
                    }
                }
            }
            $rule['conditions_parsed'] = $conditions_parsed;

            // parse action
            $action_parsed = json_decode($rule['action'], true);
            $rule['action_parsed'] = $action_parsed;
            $this->view->rule = $rule;
        }
    }    

    public function importrulesAction()
    {
        $msg = "";
        print_r($_FILES);
        if (!empty($_FILES['fileToUpload']['tmp_name']) && $_FILES['fileToUpload']['tmp_name'] !== 'none')
        {
            $objPHPExcel = PHPExcel_IOFactory::load($_FILES['fileToUpload']['tmp_name']);
            $data = $objPHPExcel->getActiveSheet()->toArray();

            $listSku = array();
            foreach ($data as $item)
            {
               if($item[1] != 1){
                    $listSku[] = $item[0];
               }
            }
            @unlink($_FILES['fileToUpload']);
            echo json_encode(array('data' => $listSku));
        }else{
            echo json_encode(array('data' => $_FILES));
        }

        $this->_helper->viewRenderer->setNoRender(true);
    }

    /**
     *
     */
    public function deleteruleAction()
    {
        // response json
        $this->_helper->viewRenderer->setNorender();

        $rule_id = $_GET['rule_id'];
        $shippingTimeModel = new QShippingtime();
        $result = $shippingTimeModel->deleteRule($rule_id);

        // response
        echo $result;
    }

    /**
     *
     */
    public function approveruleAction()
    {
        // response json
        $this->_helper->viewRenderer->setNorender();

        // response json
        $shippingTimeModel = new QShippingtime();
        $shippingTimeModel->truncate('rule_compile');
        $shippingTimeModel->copyData('rule', 'rule_compile');

        $this->_redirect('shippingtime/listrule');
    }

    /**
     *
     */
    public function swapruleorderAction()
    {
        // response json
        $this->_helper->viewRenderer->setNorender();

        $rule_id1 = $_GET['rule_id1'];
        $rule_id2 = $_GET['rule_id2'];
        $rule_order1 = $_GET['rule_order1'];
        $rule_order2 = $_GET['rule_order2'];

        $shippingTimeModel = new QShippingtime();
        $result = $shippingTimeModel->updateRule(array('order' => $rule_order2), $rule_id1);
        $result = $shippingTimeModel->updateRule(array('order' => $rule_order1), $rule_id2);

        // response
        echo $result;
    }

    /**
     *
     */
    public function importruleAction()
    {
        $this->_helper->viewRenderer->setNorender();

        $uploaded_file = $_FILES['rules_file'];

        if ($uploaded_file['name'] == null || empty($uploaded_file['name']))
            $this->_redirect('/shippingtime/listrule');

        $objPHPExcel = PHPExcel_IOFactory::load($uploaded_file['tmp_name']);
        $data = $objPHPExcel->getActiveSheet()->toArray();

        $shippingTimeModel = new QShippingtime();
        $shippingTimeModel->truncate('rule');
        $rule = array();
        foreach ($data as $key => $value)
        {
            // validate tile header
            if ($key == 0)
                continue;

            $rule['order'] = $value[1];
            $rule['conditions'] = $value[2];
            $rule['action'] = $value[3];
            $rule['comment'] = $value[4];
            $rule['enabled'] = $value[5];
            $shippingTimeModel->insertRule($rule);
        }
        $this->_redirect('/shippingtime/listrule');
    }

    /**
     *
     */
    public function exportruleAction()
    {
        $this->_helper->viewRenderer->setNorender();

        $shippingTimeModel = new QShippingtime();
        $rules = $shippingTimeModel->getRules();
        $header = array('Id', 'Order', 'Conditions', 'Result', 'Comment', 'Enabled');
        self::exportToExcel($rules, true, $header, 'rule.xls');
    }

    /**
     * 
     */
    public function importlocationAction()
    {
        $this->_helper->viewRenderer->setNorender();

        $uploaded_file = $_FILES['locations_file'];

        if ($uploaded_file['name'] == null || empty($uploaded_file['name']))
            $this->_redirect('/shippingtime/listlocation');

        $objPHPExcel = PHPExcel_IOFactory::load($uploaded_file['tmp_name']);
        $data = $objPHPExcel->getActiveSheet()->toArray();

        $shippingTimeModel = new QShippingtime();
        $shippingTimeModel->truncate('location');
        $location = array();
        foreach ($data as $key => $value)
        {
            // validate tile header
            if ($key == 0)
                continue;

            $location['code'] = $value[1];
            $location['name'] = $value[2];
            $location['time'] = $value[3];
            $shippingTimeModel->insertLocation($location);
        }
        $this->_redirect('/shippingtime/listlocation');
    }

    public function listlocationAction()
    {
        $shippingTimeModel = new QShippingtime();
        $this->view->locations = $shippingTimeModel->getLocations();
    }

    public function listorderstatusAction()
    {
        $omsModel = new QOmslive();

        $arr_omsstatus = $omsModel->getStatusOms();

        $result = array();
        foreach ($arr_omsstatus as $status)
        {
            $displayStatusId = $status['id_status_display'];
            $result[$displayStatusId]['text'] = $status['text'];
            $result[$displayStatusId]['order_item_status'][] = $status['fk_id_sales_order_item_status'];
        }

        foreach ($result as &$status)
        {
            // parse order_item_status to string
            $order_item_status = $status['order_item_status'];
            $status['order_item_status_string'] = implode(',', $order_item_status);
        }
        $this->view->orderstatus = $result;
    }

    ////////////////////action function end//////////////////////////////
    ////////////////////loggic function start//////////////////////////////
    /**
     * 
     */
    private function parseRule($data)
    {
        $rule['order'] = isset($data['order']) ? $data['order'] : 0;
        $rule['comment'] = isset($data['comment']) ? $data['comment'] : '';
        $rule['enabled'] = isset($data['enabled']) && $data['enabled'] == 'on' ? 1 : 0;

        // parse conditions
        $conditions = array();
        if (isset($data['condition_tyles']))
        {
            $condition_types = $data['condition_tyles'];
            $condition_opertors = $data['condition_operators'];
            $condition_params = $data['condition_params'];
            foreach ($condition_types as $index => $condition_tyle)
            {
                $cond = array();
                $cond['type'] = $condition_tyle;
                $cond['operator'] = $condition_opertors[$index];
                $cond['params'] = explode(',', $condition_params[$index]);
                $conditions[] = $cond;
            }
        }

        $rule['conditions'] = empty($conditions) ? '' : json_encode($conditions);

        // parse action
        $action = array();
        $action['type'] = $data['action_type'];
        $action['rule_stop'] = isset($data['action_rule_stop']) && $data['action_rule_stop'] == 'on' ? 1 : 0;

        if (isset($data['action_value']))
            $action['value'] = $data['action_value'];
        
        if (isset($data['action_offset']))
        	$action['offset'] = $data['action_offset'];
        
        if (isset($data['action_text_display']))
        	$action['text_display'] = $data['action_text_display'];
        
        
        $rule['action'] = json_encode($action);

        // 
        return $rule;
    }

    /**
     * convert string condition to array
     * @param type $strCondition
     * @return type
     */
    private function getOperatorNumberParam($operator)
    {
        $operatorConf = array
            (
            'equal' => 1,
            'not_equal' => 1,
            'less_than' => 1,
            'less_than_equal' => 1,
            'greater_than' => 1,
            'greater_than_equal' => 1,
            'in' => 'multi',
            'not_in' => 'multi',
            'between' => 'multi',
        );

        if (!isset($operatorConf[$operator]))
            return false;
        return $operatorConf[$operator];
    }

    private function parseCondition($strCondition)
    {
        // define
        $parsed_error = '<span class="warning">parsed error</span>';

        if ($strCondition == null || empty($strCondition))
            return '<font color="blue">always true</font>';

        $conditions = json_decode($strCondition, true); //var_dump($conditions);
        if ($conditions == null)
            return $parsed_error;

        $str_parsed = '';
        foreach ($conditions as $key => $condition)
        {
            //type
            $conditionTypeConvert = array
                (
                'RULE_CONDITION_LOCATION' => 'location',
                'RULE_CONDITION_SKU' => 'sku',
                'RULE_CONDITION_DATE' => 'date',
                'RULE_CONDITION_STOCK' => 'stock',
            );
            if (!isset($conditionTypeConvert[$condition['type']]))
                return $parsed_error;
            $type = $conditionTypeConvert[$condition['type']];

            // operator
            if (!isset($condition['params'][0]))
                return $parsed_error;

            $operator = $condition['operator'];
            $numberParams = $this->getOperatorNumberParam($operator);
            if ($numberParams === false)
                return $parsed_error;

            if ($numberParams == 1)
                $params = $condition['params'][0];
            elseif ($numberParams == 'multi')
                $params = $this->parseParamsToString($condition['params']);




            // convert to string
            $and = $key != 0 ? '<font color="blue">AND</font>' : '';
            $str_parsed .= "<p>{$and} <b>{$type}</b> <font color='blue'>{$operator}</font> <b>{$params}</b></p>";
        }
        return $str_parsed;
    }

    /**
     * convert array params to string
     * @param type $params
     * @return string
     */
    private function parseParamsToString($params)
    {
        $strParams = '[' . implode($params, ', ') . ']';
        $paramLenght = strlen($strParams);
        if ($paramLenght > 100)
        {
            $strParams = substr($strParams, 0, 10) . '...' . substr($strParams, -10, 10);
        }


        return $strParams;
    }

    /**
     * convert string condition to array
     * @param type $strAction
     * @return string
     */
    private function parseAction($strAction)
    {
        // define
        $parsed_error = '<span class="warning">parsed error</span>';

        if ($strAction == null || empty($strAction))
            return 'none';

        $action = json_decode($strAction, true);
        if ($action === null)
            return $parsed_error;

        $stop = '';
        if (isset($action['rule_stop']) && $action['rule_stop'] == 1)
        {
        	$text_display ='';	
            $stop = "<font color=red> (stop processing rule {$text_display})</font>";
        }
        // parse
        $str = '';
        
        
        $offset = isset($action['offset']) ? $action['offset'] : 0;       
        switch ($action['type'])
        {
            case 'RULE_ACTION_ADD_TIME':
            	$value = isset($action['value']) ? $action['value'] : 0;            	
            	if($offset != 0)            		
                	return "<span class='action_type'>add</span> {$value}h-".($value + $offset)."h  {$stop}";
            	else
            		return "<span class='action_type'>add</span> " . $action['value'] ."h  {$stop}";
            case 'RULE_ACTION_GET_LOCATION_TIME':
            	if($offset != 0)            		
                	return  "<span class='action_type'>add</span>  location time + {$offset}h $stop ";
            	else
            		return  "<span class='action_type'>add</span>  location time {$stop}" ;
                
            case 'RULE_ACTION_SET_TARGET_TIME':
            	$value = isset($action['value']) ? $action['value'] : 0;
                return "<span class='action_type'>set date</span> {$value} {$stop}" ;
            default:
                return $parsed_error;
        }
    }

    ////////////////////loggic function end//////////////////////////////

    public static function exportToExcel($data, $output = false, $header = null, $filename = null, $starRow = 1, $starCol = 'A')
    {
        //print_r($data);
        $objPHPExcel = new PHPExcel();

        $objPHPExcel->getProperties()->setCreator("product team")
                ->setLastModifiedBy("product team")
                ->setTitle("Office 2007 XLSX Test Document")
                ->setSubject("Office 2007 XLSX Test Document")
                ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");


        $objPHPExcel->setActiveSheetIndex(0);
        $sheet = $objPHPExcel->getActiveSheet();

        $col = $starCol;
        $row = $starRow;

        if ($header != null)
        {
            $sharedStyle1 = new PHPExcel_Style();
            $sharedStyle1->applyFromArray
                    (
                    array(
                        'fill' => array(
                            'type' => PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('argb' => 'D9EAED')
                        ),
                        'borders' => array(
                            'bottom' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
                            'right' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
                            'left' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
                            'top' => array('style' => PHPExcel_Style_Border::BORDER_THIN)
                        )
                    )
            );

            $arrKey = $header;
            $max = sizeof($arrKey);
            $i = 1;

            foreach ($arrKey as $key)
            {
                $cel = $col . $row;
                $sheet->setCellValue($cel, $key);
                if ($i == $max)
                {
                    break;
                }
                $i++;
                $col++;
            }
            $sheet->setSharedStyle($sharedStyle1, $starCol . $starRow . ':' . $col . $row);
            $row++;
            $col = "A";
        }
        foreach ($data as $keyRow => $rowData)
        {
            //print_r($row);
            foreach ($rowData as $val)
            {
                $cel = $col . $row;
                //echo $cel;
                $sheet->setCellValue($cel, $val);

                $col++;
            }
            $row++;
            $col = "A";
        }

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        $objWriter->save('php://output');
        if ($filename == null)
            $filename = 'export.xls';

        if ($output)
        {
            //Redirect output to a client�s web browser (Excel2007);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename=' . $filename);
            header('Cache-Control: max-age=0');
        }
    }

}

?>
